package com.sky.service.Order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.BaseContext;
import com.sky.constant.MessageConstant;
import com.sky.dto.order.OrderSelectDTO;
import com.sky.dto.order.OrderSubmitDTO;
import com.sky.dto.order.OrdersPaymentDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.utils.WeChatPayUtil;
import com.sky.utils.WebSocketServer;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 褚金龙
 * @Date 2024/10/6 10:25
 */
@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
     @Autowired
     private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param orderSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO OrderSubmit(OrderSubmitDTO orderSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
         //添加超时时间
        /*LocalDateTime CheckoutTime = LocalDateTime.now();
        LocalDateTime localDateTime = CheckoutTime.plusHours(0).plusMinutes(15);*/
        // 地址簿和购物车是否为空
        Address address = addressBookMapper.getById(orderSubmitDTO.getAddressBookId(), userId);
        if(address==null){
            // 抛出业务异常
           throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前购物车的状态
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> cartList = shoppingCartMapper.list(shoppingCart);
        if(cartList==null || cartList.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2. 向订单表插入1条数据
        Orders orders=new Orders();
        String name="";

        for (ShoppingCart cart : cartList) {
            name+=cart.getName()+ "x"+ cart.getNumber() +";";

        }
        BeanUtils.copyProperties(orderSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now()); //下单时间
        orders.setPayStatus(Orders.UN_PAID);  //还未支付
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //订单编号
        orders.setPhone(address.getPhone()); //收货人手机号
        orders.setConsignee(address.getConsignee()); //收货人
        orders.setAddress(address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail());//收货地址
        /*orders.setCheckoutTime(localDateTime);*/
        orders.setName(name);

        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList=new ArrayList<>();
        // 3.向订单明细表插入n条数据
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
        //批量插入订单详情
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空当前用户的购物车数据
         shoppingCartMapper.deleteCart(userId);
        // 封装VO返回结果
         OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
                 .id(orders.getId())
                 .order_ime(orders.getOrderTime())
                 .orderNumber(orders.getNumber())
                 .orderAmount(orders.getAmount())
                 .phone(address.getPhone())
                 .estimated_delivery_time(orders.getEstimatedDeliveryTime())
                 .address(orders.getAddress())
                 .consignee(orders.getConsignee())
                 .build();

        return orderSubmitVO;


    }



    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信下单接口，生成预支付交易单
       /* JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        //跳过微信支付
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",1);

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
         //修改订单
        paySuccess(ordersPaymentDTO.getOrderNumber());

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;


    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo,userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息，type, orderId,content

        Map map=new HashMap();
        map.put("type",1);//1表示来单提醒，2 表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 根据订单编号删除订单
     * @param orderNumber
     */
    @Override
    public void delete(String orderNumber) {
        orderMapper.delete(orderNumber);
    }




    /**
     * 管理端接口 查询所有订单
     * @return
     */
    @Override
    public PageResult select(OrderSelectDTO orderSelectDTO) {
       PageHelper.startPage(orderSelectDTO.getPage(), orderSelectDTO.getPageSize());

        Page<Orders> orders = orderMapper.select(orderSelectDTO);


        return new PageResult(orders.getTotal(),orders);
    }


    /**
     * 管理端修改订单状态
     * @param id
     * @param status
     */
    @Override
    public void updateOrderStatus(Long id, Integer status) {
        Orders orders=new Orders();
        if(status==5){
            orders.setDeliveryTime(LocalDateTime.now());
        }
        if(status==6){
            orders.setCancelTime(LocalDateTime.now());
        }
        if(status==7){
            orders.setRejectionReason("超过配送距离");
        }
        orders.setStatus(status);
        orders.setId(id);
        orderMapper.update(orders);
    }

    /**
     * 根据id删除订单
     * @param id
     */
    @Override
    public void remove(Long id) {
        orderMapper.remove(id);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
      Orders orders=  orderMapper.getById(id);

      //校验订单是否存在
        if(orders==null || orders.getStatus()==Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //给管理端浏览器推送消息
        //通过websocket向客户端浏览器推送消息，type, orderId,content

        Map map=new HashMap();
        map.put("type",2);//1表示来单提醒，2 表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

}
